package com.ct.ecommerce.order.controller;

import com.ct.ecommerce.api.order.client.OrderService;
import com.ct.ecommerce.api.order.dto.OrderDTO;
import com.ct.ecommerce.api.order.dto.OrderItemDTO;
import com.ct.ecommerce.framework.core.BeanCopierUtils;
import com.ct.ecommerce.framework.core.response.R;
import com.ct.ecommerce.framework.enums.ECommerceCodeEnum;
import com.ct.ecommerce.framework.exception.CustomerException;
import com.ct.ecommerce.framework.security.SecurityContextHolderUtils;
import com.ct.ecommerce.order.vo.handle.OrderCreateVO;
import com.google.common.base.Preconditions;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author changtong
 * @since 2021/5/23
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Resource
    private OrderService orderService;

    @PostMapping("")
    @PreAuthorize("hasAuthority('order:create')")
    public R<Long> create(@RequestBody OrderCreateVO params) {
        try {
            checkOrderForm(params);
            OrderDTO order = BeanCopierUtils.copyProperties(params, OrderDTO.class);
            List<OrderItemDTO> items =
                BeanCopierUtils.copyPropertiesOfList(params.getItems(), OrderItemDTO.class);
            order.setItems(items);
            order.setUserId(SecurityContextHolderUtils.getUser().getUserId());
            Long pk = orderService.createOrder(order);
            return R.ok(pk);
        } catch (CustomerException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("创建订单出错 : ", e);
            return R.fail(e.getMessage());
        }
    }



    private void checkOrderForm(OrderCreateVO form){
        Preconditions.checkNotNull(form, ECommerceCodeEnum.ORDER_INFO_ERROR.getMessage());
        Preconditions.checkArgument(!CollectionUtils.isEmpty(form.getItems()), ECommerceCodeEnum.ORDER_INFO_ERROR.getMessage());
    }


}
